import json

import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import re


# 设置URL
url = 'https://data.eastmoney.com/zrt/zrqHistory/688271.html'

url = 'https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery11230786842473102177_1718457245053&sortColumns=TRADE_DATE&sortTypes=-1&pageSize=50&pageNumber=1&reportName=RPT_REFINANCE_TRAN_DEL&columns=ALL&source=WEB&client=WEB&filter=(SECURITY_CODE%3D%22688271%22)'

url = 'https://datacenter-web.eastmoney.com/api/data/v1/get'
params = {
    'callback': 'jQuery11230786842473102177_1718457245053',
    'sortColumns': 'TRADE_DATE',
    'sortTypes': -1,
    'pageSize': 50,
    'pageNumber': 1,
    'reportName': 'RPT_REFINANCE_TRAN_DEL',
    'columns': 'ALL',
    'source': 'WEB',
    'client': 'WEB',
    'filter': '(SECURITY_CODE="688271")'
}

headers = {
    'Accept':'*/*',
    'Accept-Encoding':'gzip, deflate, br, zstd',
    'Accept-Language':'zh-CN,zh;q=0.9',
    'Connection':'keep-alive',
    'Cookie':'qgqp_b_id=ecacdafacf19708666eb3adbb0f69a4c; st_si=23310874661494; websitepoptg_api_time=1718450229554; st_asi=delete; HAList=ty-105-API-%u58F0%u7F51; st_pvi=76026277595136; st_sp=2023-12-02%2019%3A19%3A57; st_inirUrl=http%3A%2F%2Fquote.eastmoney.com%2Fredirect.html; st_sn=10; st_psi=2024061521140686-113300301000-8596016326; JSESSIONID=644BF22B473860900852C9610B6C4A67',
    'Host':'datacenter-web.eastmoney.com',
    'Referer': 'https://data.eastmoney.com/zrt/zrqHistory/688271.html',
    'Sec-Ch-Ua':'Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
    'Sec-Ch-Ua-Mobile':'?0',
    'Sec-Ch-Ua-Platform':"macOS",
    'Sec-Fetch-Dest':'script',
    'Sec-Fetch-Mode':'no-cors',
    'Sec-Fetch-Site':'same-site',
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}
response = requests.get(url,params=params, headers=headers)
print(response.text)

# 检查请求是否成功
if response.status_code == 200:
    # 解析HTML内容
    match = re.search(r'\(([^()]*)\)', response.text)
    if match:
        json_str = match.group(1)
        try:
            data = json.loads(json_str)
            # print(data['result']['data'])
            for rec in data['result']['data']:
                print(rec)
                record = {'code': rec['SECURITY_CODE'], 'shortName': rec['SECURITY_NAME_ABBR'], 'tradeDate': rec['TRADE_DATE'], 'begBalanceNum': rec['BEG_BALANCE_NUM'], 'endBalanceNum': rec['END_BALANCE_NUM'],
                          'marginSecFinNum': rec['MARGINSEC_FIN_NUM'], 'endBalance': rec['END_BALANCE'], 'marketCap': rec['MARKET_CAP'], 'closingPrice': rec['CLOSE_PRICE'],
                          'changeRate': rec['CHANGE_RATE'], 'exchange': rec['SECUCODE'], 'innerCode': rec['SECURITY_INNER_CODE'], 'createdTime': datetime.datetime.now(),
                          'source': 'EAST'}
                qCon = {''}

                print(record)

        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")


else:
    print("请求失败")